<template>

  <div class="wrapper">

    <van-cell :title="address.detail" label="选择收货地址"  is-link to="/address/list"/>

    <div class="content">
      <ul>
        <li v-for="cart in cartList">
          <van-card
              :num="cart.count"
              :price="cart.price"
              :desc="cart.description"
              :title="cart.name"
              :thumb="cart.photo"
          >
              <template #tags v-if="cart.flavorItem">
                <van-tag plain type="success" style="margin-right: 4px;">{{cart.flavorItem}}</van-tag>
                <van-tag plain type="danger">{{cart.flavorValue}}</van-tag>
              </template>
          </van-card>
        </li>

      </ul>


      <van-field
          v-model="remark"
          rows="1"
          autosize
          label="留言"
          type="textarea"
          placeholder="请输入留言"
      />



      <van-cell :value="'总价'+amount" />
    </div>

    <van-submit-bar :price="amount*100" button-text="提交订单" @submit="handleAddBook"/>
  </div>
</template>


<script setup lang="ts">
import {ref, reactive,computed} from 'vue';
import {useRouter} from 'vue-router';

import {getCartList} from "@/api/cart.js"
import {getDefaultAddress} from "@/api/address.js"
import {addBook} from "@/api/book.js"

const router = useRouter();

const cartList = reactive([]);

//收获地址
const address= ref({});
const remark= ref("");

//计算总价
const amount = computed(() => {
  let amount = 0;
  for(let cart of cartList){
    amount+=(cart.price*cart.count);
  }
  return amount;
});

const loadCartList= ()=>{
  getCartList().then((resp)=>{
    cartList.length = 0;
    cartList.push(... resp.data);
  })
}

const loadDefaultAddress= ()=>{
  getDefaultAddress().then((resp)=>{
    if(resp.code == 200){
      address.value = resp.data;
    }
  })
}

const handleAddBook=()=>{
  if(address.value.id){
    addBook(address.value.id,remark.value).then((resp)=>{
      if(resp.code == 200){
        //代表下单成功  获取到订单的编号和总金额
        router.push({"path":"/pay/pay","query":{"num":`${resp.data.num}`,"amount":`${resp.data.amount}`}})
      }else{
        showNotify({ message: resp.msg });
      }
    })
  }else{
    showNotify({ message: '请选择收获地址' });
  }
}

 
loadCartList();

loadDefaultAddress();

</script>

<style scoped>

.wrapper {
  padding: 10px;
}

.wrapper ul {
  margin-top: 10px;
}

.wrapper ul li{
  background-color: #fff;
  border-bottom: 1px solid #F6F7F8;
}
.wrapper ul li:first-child{
  margin-top: 0;
}

::v-deep .van-card {
  background-color: #fff;
}
</style>
